<template>
  <div
    ref="refText"
    :id="'richText' + props.name"
    :key="key"
    :style="
      (width ? 'width:' + width + 'px;' : '') +
      (height ? 'height:' + (height - 44) + 'px' : '')
    "
  ></div>
  <!-- <div id="richText" :key="key"></div> -->
</template>

<script lang="ts" setup>
import uniqueid from 'lodash.uniqueid';
import WangEditor from 'wangeditor';
import { DomEditor, createEditor } from '@wangeditor/editor';

const { $, BtnMenu, DropListMenu, PanelMenu, DropList, Panel, Tooltip } =
  WangEditor;

const editor = ref();

const key = uniqueid('richtext-');
const richTxt = ref('');
let refText = ref();
const props = withDefaults(
  defineProps<{
    content?: string;
    disabled?: boolean;
    name?: string;
    hideToolBar?: boolean;
    width?: number;
    height?: number;
  }>(),
  {}
);
watch(
  () => props.content,
  (val) => {
    nextTick(() => {
      if (val !== richTxt.value) {
        richTxt.value = props.content as string;
        editor.value.$textElem.elems[0].innerHTML = '';
        editor.value.$textElem.html(props.content);
      }
    });
  }
);
const emit = defineEmits(['update:content']);
watch(
  () => richTxt.value,
  (val) => {
    emit('update:content', val);
  }
);
const insertContent = (content: any) => {
  editor.value.cmd.do('insertHTML', content);
};
defineExpose({ insertContent });

// 分页操作
class SwitchLine extends BtnMenu {
  constructor(editor) {
    // data-title属性表示当鼠标悬停在该按钮上时提示该按钮的功能简述
    const $elem = WangEditor.$(
      `<div class="w-e-menu" data-title="switchLine">
                <span>分页</span>
            </div>`
    );
    super($elem, editor);
  }
  // 菜单点击事件
  clickHandler() {
    // 做任何你想做的事情
    // 可参考【常用 API】文档，来操作编辑器
    this.editor.cmd.do('insertHTML', '<div class="page-break"><br/></div>');
  }
  // 菜单是否被激活（如果不需要，这个函数可以空着）
  // 1. 激活是什么？光标放在一段加粗、下划线的文本时，菜单栏里的 B 和 U 被激活，如下图
  // 2. 什么时候执行这个函数？每次编辑器区域的选区变化（如鼠标操作、键盘操作等），都会触发各个菜单的 tryChangeActive 函数，重新计算菜单的激活状态
  tryChangeActive() {
    // 激活菜单
    // 1. 菜单 DOM 节点会增加一个 .w-e-active 的 css class
    // 2. this.this.isActive === true
    this.active();

    // // 取消激活菜单
    // // 1. 菜单 DOM 节点会删掉 .w-e-active
    // // 2. this.this.isActive === false
    // this.unActive()
  }
}

const switchLine = 'switchLine'; // 工具栏分页
// Boot.registerMenu(myMenuConf);
WangEditor.registerMenu(switchLine, SwitchLine);

const init = () => {
  const editor1: any = new WangEditor('#richText' + props.name);
  editor1.menus.extend(switchLine, SwitchLine);
  // 配置 onchange 回调函数，将数据同步到 vue 中
  editor1.config.onchange = (newHtml: any) => {
    richTxt.value = newHtml;
  };
  editor1.config.zIndex = 500;
  editor1.config.uploadImgShowBase64 = true;
  editor1.config.showLinkImg = false;
  if (props.height) editor1.config.height = props.height - 44 + 'px';
  // editor1.config.insertKeys = {
  //   index: 0,
  //   keys: ['myMenu']
  // };
  editor1.config.menus = [
    switchLine,
    'head',
    'bold',
    'fontSize',
    'fontName',
    'italic',
    'underline',
    'strikeThrough',
    'indent',
    'lineHeight',
    'foreColor',
    'backColor',
    'link',
    'list',
    'todo',
    'justify',
    // 'quote',
    // 'emoticon',
    'image',
    'video',
    'table',
    'code',
    'splitLine',
    'undo',
    'redo'
  ];

  // 创建编辑器
  editor1.create();

  editor.value = editor1;
  if (props.content) {
    // console.log('editor.value', editor.value);
    editor.value.$textElem.html(props.content);
  }
  if (props.disabled) {
    editor1.disable();
  }
};
nextTick(() => {
  init();
});

onBeforeUnmount(() => {
  // 调用销毁 API 对当前编辑器实例进行销毁
  editor.value.destroy();
  editor.value = null;
});
onActivated(() => {
  // console.log('active');

  key.value = uniqueid('richtext-');
});
</script>

<style lang="less" scoped>
#richText {
  width: 100%;
  .w-e-toolbar {
    border-top-left-radius: 4px;
    border-top-right-radius: 4px;
  }
  :deep(.w-e-text-container) {
    border-bottom-right-radius: 4px;
    border-bottom-left-radius: 4px;
  }
}
</style>
